﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using TimKen.DataAccess;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.SessionState;
using TimKen.DataEntity;

namespace TimKen.Web.Ashx
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Comments : IHttpHandler, IRequiresSessionState
    {
        private const int PageSize = 2;
        private string GetPageCount()
        {
            string productId = HttpContext.Current.Request.QueryString["ProductID"];
            string sql = "";
            sql = string.Format("select  COUNT(*) from PComment where ProductID={0}", productId);
            object o = DbHelperSQL.GetSingle(sql);

            int rowcount = 0;

            if (o != null)
                rowcount = Convert.ToInt32(o);
            return (Math.Ceiling((decimal)rowcount / PageSize)).ToString();
        }

        private string GetPageData(string p, string productId)
        {
            int PageIndex = int.Parse(p);
            string sql;
            if (PageIndex == 1)
                sql = "select top " + PageSize.ToString() + " * from PComment  WHERE  ProductID={0} order by CommentID desc ";
            else
                sql = "select top " + PageSize.ToString() + " * from PComment  where  ProductID={0}  AND CommentID not in(select top " + ((PageIndex - 1) * PageSize).ToString() + " CommentID from PComment  WHERE  ProductID={0}  order   by CommentID desc)  order by CommentID desc ";

            string data = "{{\"CommentID\":\"{0}\",\"Content\":\"{1}\",\"Creator\":\"{2}\",\"CreateTime\":\"{3}\"}},";
            StringBuilder sb = new StringBuilder();
            sb.Append("[");

            sql = string.Format(sql, productId);
            SqlDataReader comments = DbHelperSQL.ExecuteReader(sql);
            while (comments.Read())
            {
                sb.Append(string.Format(data, comments["CommentID"].ToString(), comments["Content"].ToString(), comments["Creator"].ToString(), comments["CreateTime"].ToString()));
            }
            sb.Remove(sb.Length - 1, 1);

            comments.Close();

            sb.Append("]");

            return sb.ToString();
        }

        public void ProcessRequest(HttpContext context)
        {
            string action = HttpContext.Current.Request.QueryString["action"];

            if (action == "getlist")
            {
                context.Response.ContentType = "application/json";
                context.Response.Charset = "utf-8";


                string productId = HttpContext.Current.Request.QueryString["ProductID"];
                string result = "";
                if (context.Request.Params["getPageCount"] != null)
                    result = GetPageCount();
                if (context.Request.Params["pageIndex"] != null)
                {
                    string pageindex = context.Request.Params["pageIndex"];
                    result = GetPageData(context.Request.Params["pageIndex"], productId);
                }
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.Write(result);
            }
            if (action == "add")
            {

                string productId = HttpContext.Current.Request.Params["ProductID"];
                string content = HttpContext.Current.Request.Params["Content"];

                string CurrentUserName = context.Session["User"] == null ? "未注册" : ((UserS)context.Session["User"]).UserName;
                string sql = "INSERT  PComment(Creator,[Content],ProductID)  VALUES ('{0}','{1}',{2})";
                sql = string.Format(sql, CurrentUserName, content, productId);
                DbHelperSQL.ExecuteSql(sql);

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
